package com.mo.admin.security.config;

import com.mo.admin.security.filters.JwtOncePerRequestFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


// 新配置方式
@EnableWebSecurity
// 开启方法权限校验
@EnableMethodSecurity()
@Configuration
public class SecurityConfig {
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    @Resource
    private JwtOncePerRequestFilter jwtOncePerRequestFilter;

    // 添加密码加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 暴露验证管理器，在 LoginController 中使用
    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService);
        // 配置 setHideUserNotFoundExceptions(false) 后，UsernameNotFoundException 将不会被转换为 BadCredentialsException，而是直接抛出
        provider.setHideUserNotFoundExceptions(false);
        provider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(provider);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 允许跨域
                .cors(Customizer.withDefaults())
                // 禁用 CSRF 跨域请求伪造
                .csrf(AbstractHttpConfigurer::disable)
                // 设置无session的会话（使用token）
                .sessionManagement(management ->
                        management.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                // 配置授权规则，登录接口允许匿名访问，其他请求需要认证
                .authorizeHttpRequests(authorize ->
                        authorize.requestMatchers("/login").anonymous()
                                .anyRequest().authenticated()
                )
                // 禁用默认的登出功能
                .logout(AbstractHttpConfigurer::disable)
                // 添加 JWT 过滤器
                .addFilterBefore(jwtOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class)
                // 异常处理
                .exceptionHandling(handler ->
                        handler.authenticationEntryPoint(authenticationEntryPoint)
                                .accessDeniedHandler(accessDeniedHandler)
                );
        return http.build();
    }
}